import subprocess
import os
import shutil

def run_mvn_build_and_dockerize():
    # ======================
    # 1. 获取目录信息
    # ======================

    # 当前脚本所在目录
    script_dir = os.getcwd()
    print(f"📍 当前脚本目录: {script_dir}")

    # 上一级目录 = Maven 项目根目录（含 pom.xml）
    project_root = os.path.abspath(os.path.join(script_dir, ".."))
    print(f"🎯 Maven 项目根目录: {project_root}")

    # 目标 JAR 拷贝目录：../../docker/ruoyi/gateway/jar/
    jar_dest_dir = os.path.abspath(os.path.join(script_dir, "../../docker/ruoyi/gateway/jar"))
    print(f"📦 JAR 拷贝目标目录: {jar_dest_dir}")

    # Docker 构建目录：../../docker/ruoyi/gateway/ （含 Dockerfile）
    docker_build_dir = os.path.abspath(os.path.join(script_dir, "../../docker/ruoyi/gateway"))
    print(f"🐳 Docker 构建目录（将执行 docker build）: {docker_build_dir}")

    # ======================
    # 2. 执行 Maven 打包
    # ======================

    mvn_command = ["mvn", "clean", "package", "-Dmaven.test.skip=true"]
    try:
        print("🚀 开始执行 Maven 打包命令: mvn clean package -Dmaven.test.skip=true")
        subprocess.run(mvn_command, cwd=project_root, check=True, text=True)
        print("✅ Maven 打包成功！")
    except subprocess.CalledProcessError as e:
        print("❌ Maven 打包失败！")
        print("错误码:", e.returncode)
        print("错误信息:")
        print(e.stderr)
        return
    except Exception as e:
        print("⚠️ 执行 Maven 时发生未知错误:", e)
        return

    # ======================
    # 3. 查找并拷贝 JAR 文件
    # ======================

    target_dir = os.path.join(project_root, "target")
    if not os.path.isdir(target_dir):
        print(f"❌ 未找到 target 目录: {target_dir}")
        return

    jar_files = [f for f in os.listdir(target_dir) if f.endswith(".jar")]
    if not jar_files:
        print(f"❌ 在 {target_dir} 下未找到任何 .jar 文件")
        return

    jar_filename = jar_files[0]  # 取第一个 jar，通常是主包
    source_jar_path = os.path.join(target_dir, jar_filename)
    print(f"📦 找到 JAR 文件: {source_jar_path}")

    # 确保 jar 目标目录存在
    os.makedirs(jar_dest_dir, exist_ok=True)

    # 拷贝 jar 到 docker/gateway/jar/
    dest_jar_path = os.path.join(jar_dest_dir, jar_filename)
    try:
        shutil.copy2(source_jar_path, dest_jar_path)
        print(f"✅ JAR 已拷贝到: {dest_jar_path}")
    except Exception as e:
        print(f"❌ 拷贝 JAR 失败: {e}")
        return

    # ======================
    # 4. 进入 Docker 构建目录并执行 docker build
    # ======================

    if not os.path.isdir(docker_build_dir):
        print(f"❌ Docker 构建目录不存在: {docker_build_dir}，请确保该目录包含 Dockerfile")
        return

    dockerfile_path = os.path.join(docker_build_dir, "dockerfile")
    if not os.path.isfile(dockerfile_path):
        print(f"❌ dockerfile 不存在于目录: {docker_build_dir}")
        return

    print(f"🐳 准备在目录下执行 Docker 构建: {docker_build_dir}")
    print("   执行命令: docker build -t msgateway .")

    try:
        # 切换到 Docker 构建目录并运行 docker build
        subprocess.run(["docker", "build", "-t", "msgateway", "."], cwd=docker_build_dir, check=True)
        print("✅ Docker 镜像构建成功: msgateway")
    except subprocess.CalledProcessError as e:
        print("❌ Docker 构建失败！")
        print("错误码:", e.returncode)
        print("错误信息:")
        print(e.stderr)
    except Exception as e:
        print("⚠️ 执行 Docker 构建时发生未知错误:", e)
    # 创建容器
    try:
        print("🐳 准备启动 Docker 容器: docker run -d --name msgateway -p 36000 msgateway")
        subprocess.run(
            ["docker", "run", "-d", "--name", "msgateway", "-p", "36000", "msgateway"],
            cwd=docker_build_dir,  # 可以是任意目录
            check=True
        )
        print("✅ Docker 容器启动成功: msgateway (宿主机端口 随机 -> 容器端口 38080)")
    except subprocess.CalledProcessError as e:
        print("❌ Docker 容器启动失败！")
        print("错误码:", e.returncode)
        print("错误信息:")
        print(e.stderr)
    except Exception as e:
        print("⚠️ 执行 Docker 容器运行时发生未知错误:", e)

if __name__ == "__main__":
    run_mvn_build_and_dockerize()